package cn.afactory.tygz.sns.weixin;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.Log;

import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URL;

import cn.afactory.tygz.sns.Constants;
import cn.afactory.tygz.sns.lsn.OnSnsResponseListener;
import cn.afactory.tygz.R;

public class WeiXinController {
	private String TAG = "WeiXinController";
	private static final int THUMB_SIZE = 150;
	private static WeiXinController Instance;
	private IWXAPI api;
	private Context mContext;
	private Activity mActivity;
	
	public static WeiXinController getInstance(Activity activity){
		if(Instance == null){
			Instance = new WeiXinController(activity);
		}
		return Instance;
	}
	
	public WeiXinController(Activity activity){
		mActivity = activity;
		mContext = activity;
	}
	
	public void init(){
		api = WXAPIFactory.createWXAPI(mActivity, Constants.WEIXIN_SHARE_ID, false);
		registerToWX();
	}
	
	private void registerToWX(){
		 api.registerApp(Constants.WEIXIN_SHARE_ID);
	}
	
	public void sendTextMessage(
			String text,
			String description,
			String imageLocal,
			String imageUrl,
			String webUrl,
			Bitmap thumb,
			boolean isSharedTo , 
			OnSnsResponseListener lsn){
		if(!TextUtils.isEmpty(webUrl)){
			sendWebpage(text,description,webUrl,thumb,isSharedTo);
			return ;
		}
		
		WXTextObject textObj = new WXTextObject();
//		WXFileObject fileObject = new WXFileObject();
		WXMediaMessage mediaMessage = new WXMediaMessage();
		WXImageObject imageObj = new WXImageObject();
		if(!TextUtils.isEmpty(text)){
			textObj.text = text;
			mediaMessage.mediaObject = textObj;
		}
		
		if(!TextUtils.isEmpty(description)){
			mediaMessage.description = description;
		}

		if(!TextUtils.isEmpty(imageLocal)){
			File file = new File(imageLocal);
			if (file.exists()) {
				imageObj.setImagePath(imageLocal);
//			fileObject.setFilePath(imageLocal);
				mediaMessage.mediaObject = imageObj;
				
				Bitmap bmp = BitmapFactory.decodeFile(imageLocal);
				if(bmp == null) return;
				Bitmap thumbBmp = imageZoom(bmp);
				bmp.recycle();
				mediaMessage.thumbData = bmpToByteArray(thumbBmp, true);
				
				SendMessageToWX.Req req = new SendMessageToWX.Req();
				req.transaction = buildTransaction("img");
				req.message = mediaMessage;
				req.scene = isSharedTo ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
				api.sendReq(req);
				return;
			}			
		}
		
		if(!TextUtils.isEmpty(imageUrl)){
//			imageObj.imageUrl = imageUrl;
//			mediaMessage.mediaObject = imageObj;
            try {
                WXImageObject imgObj = new WXImageObject();
                imgObj.imageUrl = imageUrl;

                mediaMessage.mediaObject = imgObj;
                Bitmap bmp = BitmapFactory.decodeStream(new URL(imageUrl).openStream());
				if(bmp == null) return;
                Bitmap thumbBmp = imageZoom(bmp);

                mediaMessage.thumbData = bmpToByteArray(thumbBmp, true);
                bmp.recycle();

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("img");
                req.message = mediaMessage;
                req.scene = isSharedTo ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
                api.sendReq(req);
                return;
            }catch(Exception ex){

            }
		}

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		if(req.transaction == null) req.transaction = buildTransaction("text"); 
		req.message = mediaMessage;
		req.scene = isSharedTo ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
		
		api.sendReq(req);
	}
	
	private void sendWebpage(
			String title,
			String description,
			String webUrl,
			Bitmap thumb,
			boolean isSharedToCircle ){
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = webUrl;
		WXMediaMessage msg = new WXMediaMessage(webpage);
		if(title != null){
			msg.title = title;
		}
		if(description != null){
			msg.description = description;
		}
		
		if(thumb == null){
			thumb = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
		}
		Log.d(TAG, "loza,title:"+title+",description:"+description+",webUrl"+webUrl);
		msg.thumbData = bmpToByteArray(thumb, true);
		
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		req.scene = isSharedToCircle ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
		api.sendReq(req);
	}
	
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
	}
	
	public boolean isSupported(){
		return api.isWXAppInstalled() && api.isWXAppSupportAPI();
	}
	
	public IWXAPI getIwxapi(){
		return api;
	}
	
	public static byte[] utilbmpToByteArray(final Bitmap bmp, final boolean needRecycle) {

		int i;
		int j;
		if (bmp.getHeight() > bmp.getWidth()) {
			i = bmp.getWidth();
			j = bmp.getWidth();
		} else {
			i = bmp.getHeight();
			j = bmp.getHeight();
		}

		Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
		Canvas localCanvas = new Canvas(localBitmap);

		while (true) {
			localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i, j), null);
			if (needRecycle)
				bmp.recycle();
			ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
			localBitmap.compress(CompressFormat.PNG, 100, localByteArrayOutputStream);
			localBitmap.recycle();
			byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
			try {
				localByteArrayOutputStream.close();
				return arrayOfByte;
			} catch (Exception e) {
				// F.out(e);
			}
			i = bmp.getHeight();
			j = bmp.getHeight();
		}
	}

	public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try{
            bmp.compress(CompressFormat.PNG, 100, output);
            if (needRecycle) {
                bmp.recycle();
            }
        }catch (Exception e){
            e.printStackTrace();
        }


		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	private Bitmap imageZoom(Bitmap bitMap) {
		// 图片允许最大空间 单位：KB
		double maxSize = 15;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitMap.compress(CompressFormat.PNG, 100, baos);
		byte[] b = baos.toByteArray();
		double mid = b.length / 1024;
		if (mid > maxSize) {
			double i = mid / maxSize;
			 return Bitmap.createScaledBitmap(bitMap, (int) (bitMap.getWidth() / Math.sqrt(i)),
					 (int) (bitMap.getHeight() / Math.sqrt(i)), true);
		}
		return bitMap;
	}

}
